package org.teremail.util;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class IO {
    
    public final static Charset US_ASCII = Charset.forName("US-ASCII");
    public final static byte[] ENDL = { '\r', '\n' };

    /**
     * Copies an input stream to an output stream.
     * 
     * @param in
     * @param out
     * @return
     * @throws IOException
     */
    public static long copy(InputStream in, OutputStream out) throws IOException {
        byte[] data = new byte[1024];
        int numRead = 0;
        long total = 0;
        while ((numRead = in.read(data)) != -1) {
            out.write(data, 0, numRead);
            total += numRead;
        }
        return total;
    }
    
    /**
     * Reads an input stream into a string using the specified encoding.  
     * This method is a little dangerous as it places no limit on the size
     * of the string.  Use with caution.
     * 
     * @param in
     * @param encoding
     * @return
     * @throws IOException
     */
    public static String toString(InputStream in, Charset encoding) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        copy(in, out);
        return new String(out.toByteArray(), encoding);
    }
    
    /**
     * Writes all of the data out to a file specified by filename.
     * 
     * @param filename
     * @param data
     * @throws IOException
     */
    public static void write(String filename, byte[] data) throws IOException {
        FileOutputStream fout = new FileOutputStream(filename);
        fout.write(data);
        fout.flush();
        fout.close();        
    }
    

}
